/*
 * Copyright 2013-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.gateway.support.config;

import org.springframework.core.convert.converter.Converter;

/**
 * @author Marta Medio
 */
public class KeyValueConverter implements Converter<String, KeyValue> {

	private static final String INVALID_CONFIGURATION_MESSAGE = "Invalid configuration, expected format is: 'key:value', received: ";

	@Override
	public KeyValue convert(String source) throws IllegalArgumentException {
		try {
			// 使用":"分割输入的字符串source
			String[] split = source.split(":");

			// 检查分割后的数组长度是否为2
			if (split.length == 2) {
				// 如果长度为2，则创建并返回一个KeyValue对象
				// KeyValue的构造函数预计接受两个参数：键和值
				// split[0]是键，split[1]是值
				return new KeyValue(split[0], split.length == 1 ? "" : split[1]);
			}

			// 如果分割后的数组长度不为2，则抛出IllegalArgumentException异常
			// 异常信息包括一个预定义的错误消息INVALID_CONFIGURATION_MESSAGE和输入的source字符串
			throw new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE + source);
		}
		catch (ArrayIndexOutOfBoundsException e) {
			// 捕获ArrayIndexOutOfBoundsException异常
			// 这种情况理论上不会发生，因为split.length的检查已经确保了数组访问的安全
			// 但为了代码的健壮性，还是捕获了这个异常
			// 并抛出IllegalArgumentException异常
			throw new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE + source);
		}
	}

}
